﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using fanfu.Model;
using fanfu.Business;
using fanfu.Common;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

public partial class FriendLink : BasePage
{
    //所有友情链接信息
    private DataTable __FriendLink = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string linkSiteName = this.searchLinkSiteName.Value.Trim();
        byte linkType = byte.Parse(this.searchLinkType.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM FriendLink WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (linkSiteName != "")
        {
            sqlString += "AND LinkSiteName like @LinkSiteName ";
            paraList.Add(new SqlParameter("@LinkSiteName", "%" + linkSiteName + "%"));
        }
        if (linkType != 0)
        {
            sqlString += "AND LinkType=@LinkType ";
            paraList.Add(new SqlParameter("@LinkType", linkType));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        sqlString += "ORDER BY LinkType ASC, Ord ASC";
        #endregion

        //给数据列表赋值
        __FriendLink = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __FriendLink.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__FriendLink.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchLinkSiteName.Value = "";
        this.searchLinkType.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __FriendLink = new FriendLinkRule().GetAllFriendLinkInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __FriendLink.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__FriendLink.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.deleteID.Value = "";          //清除删除的ID
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true);  //JS清空控件值
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定链接类型到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchLinkType, typeof(FriendLinkType));
            EnumPlus.BindDesEnumToListControl(this.drpLinkType, typeof(FriendLinkType));
            this.drpLinkType.Items.RemoveAt(0);
            //绑定链接状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(FriendLinkFlag));
            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            FriendLinkModel friendLink = new FriendLinkRule().GetFriendLinkByID(editID);

            //绑定值到页面控件
            this.txtLinkSiteName.Value = friendLink.LinkSiteName;
            this.txtLinkUrl.Value = friendLink.LinkUrl;
            this.txtOrd.Value = friendLink.Ord.ToString();
            this.drpLinkType.ClearSelection();
            this.drpLinkType.Items.FindByValue(friendLink.LinkType.ToString()).Selected = true;
            this.chkFlag.Checked = friendLink.Flag == (byte)FriendLinkFlag.normal ? true : false;
            this.logoimg.Src = friendLink.LogoImg;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new FriendLinkRule().DeleteFriendLink(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string linkSiteName = this.txtLinkSiteName.Value.Trim();
        string linkUrl = this.txtLinkUrl.Value.Trim();
        int ord = int.Parse(this.txtOrd.Value);
        byte linkType = byte.Parse(this.drpLinkType.SelectedItem.Value);
        byte flag = this.chkFlag.Checked == true ? (byte)FriendLinkFlag.normal : (byte)FriendLinkFlag.delete;
        string logoImg = string.Empty;
        //获取当前的logo图片地址
        string oldLogoImg = logoImg = this.logoimg.Src;

        #region 上传友情链接图片
        string fileUpName = this.fupLogoImg.FileName;
        try
        {
            if (fileUpName != "")
            {
                //配置文件没有设置时则设置默认路径
                string configPath = ConfigurationManager.AppSettings["FriendLinkImagePath"];
                if (string.IsNullOrEmpty(configPath))
                    configPath = "~/Upload/FriendLinkImage/";

                //物理路径不存在则创建物理路径
                string realityPath = Server.MapPath(configPath);
                if (!Directory.Exists(realityPath))
                    Directory.CreateDirectory(realityPath);

                FileInfo fileInfo = new FileInfo(fileUpName);
                string fileType = fileInfo.Extension;
                if (".gif".Equals(fileType) || ".jpg".Equals(fileType) || ".bmp".Equals(fileType) || ".png".Equals(fileType) || ".GIF".Equals(fileType) || ".JPG".Equals(fileType) || ".BMP".Equals(fileType) || ".PNG".Equals(fileType))
                {
                    fileUpName = linkSiteName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + "-" + fileUpName;
                    logoImg = configPath + fileUpName;
                    this.fupLogoImg.SaveAs(realityPath + fileUpName);

                    //上传新Logo成功后删除原Logo
                    if (oldLogoImg != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldLogoImg)); }
                        catch (Exception ex) { }
                    }
                }
                else
                {
                    RunJavascript("PopupMsg('error','上传文件类型错误,请选择.gif、.jpg、.bmp、.png格式的图片文件！');", true);
                    RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            RunJavascript("PopupMsg('error','错误,文件上传失败！');", true);
            return;
        }
        #endregion

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            string editID = this.editID.Value;
            //更新友情链接
            string sqlString = "UPDATE FriendLink SET LinkSiteName=@LinkSiteName, LinkUrl=@LinkUrl, Ord=@Ord, LinkType=@LinkType, Flag=@Flag, LogoImg=@LogoImg WHERE ID=@ID";
            List<SqlParameter> paraList = new List<SqlParameter>();
            paraList.Add(new SqlParameter("@LinkSiteName", linkSiteName));
            paraList.Add(new SqlParameter("@LinkUrl", linkUrl));
            paraList.Add(new SqlParameter("@Ord", ord));
            paraList.Add(new SqlParameter("@LinkType", linkType));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@LogoImg", logoImg));
            paraList.Add(new SqlParameter("@ID", editID));
            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }
        else
        {
            //新增友情链接
            FriendLinkModel friendLink = new FriendLinkModel();
            friendLink.LinkSiteName = linkSiteName;
            friendLink.LinkUrl = linkUrl;
            friendLink.Ord = ord;
            friendLink.LinkType = linkType;
            friendLink.Flag = flag;
            friendLink.LogoImg = logoImg;
            int result = SqlHelper.ExecuteCommand(FriendLinkModel.GetInsertSQL(), friendLink.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}